import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router';
import { useStorage } from '@vueuse/core'
import type { RouteRecordRaw } from 'vue-router';

import Router_User from './Router_User';
import Router_Admin from './Router_Admin';
import Router_Watcher from './Router_Wacther';

const RouterMapping: { [key: string]: any } = {
    user: Router_User,
    admin: Router_Admin,
    watcher: Router_Watcher,
};


const router = createRouter({
    history: createWebHashHistory(import.meta.env.BASE_URL),
    routes: [
        { path: '/', redirect: '/main' },
        { path: '/login', component: () => import('./login.vue'), meta: { NavName: '登录', titleName: '登录' } },
    ],
});

function addRouter(routers: any) {
    routers.forEach((ele: any) => {
        router.addRoute(ele);
    });
};

function initRouter(Router?: String): void {
    const Permission = useStorage('permission', '', localStorage);
    if (!Permission.value) return;
    addRouter(RouterMapping[Permission.value]);
}

initRouter();

router.beforeEach(async (to, from) => {
    if (to.path != '/login') {
        const Token = useStorage('token', '', localStorage);
        if (!Token.value) {
            return { path: '/login' }
        }
    };
    var titleEle = document.getElementById('DOC_TITLE');
    if (titleEle) {
        titleEle.innerHTML = '代码审查 -' + to.meta.titleName
    };
});


export { router, initRouter }
